package cn.sdstudio.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.Date;

/**
 * @author zyq
 */
@Component
public class JwtUtils {
    private static final String SECRET = "MySuperSecretKeyForJWTMySuperSecretKeyForJWT";
    private static final long EXPIRATION = 7 * 24 * 60 * 60 * 1000L;

    private static final Key key = Keys.hmacShaKeyFor(SECRET.getBytes());

    public static String createToken(Long userId, String username) {
        return Jwts.builder()
                .setSubject(userId.toString())
                .claim("username", username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .signWith(key, SignatureAlgorithm.HS256)
                .compact();
    }

    public Claims parseToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(key)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    public Long getUserId(String token) {
        return Long.parseLong(parseToken(token).getSubject());
    }

    public String getUsername(String token) {
        return (String) parseToken(token).get("username");
    }
}
